package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysRoleService;
import com.bdqn.service.SysUserService;
import com.bdqn.utils.Constants;
import com.bdqn.utils.PageSupport;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger logger = Logger.getLogger(SysUserController.class);

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    //示例1,10
    @GetMapping("/add")
//    @GetMapping("/toAdd")
    public String toAdd(HttpServletRequest request) {
        return "sysUser/add";
    }

    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session) {
        SysUser create = (SysUser) session.getAttribute(Constants.USER_SESSION);
        sysUser.setCreatedUserId(create.getId());
        if (sysUserService.add(sysUser)) {
            return "redirect:/user/list";
        } else {
            return "sysUser/add";
        }
    }

    //示例4
    //查询用用户详情
    @GetMapping("/view/{id}")
    public String userview(@PathVariable Integer id, Model model) {
        logger.debug("根据id查询用户详情" + id);
        SysUser sysUser = sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    //示例6
    @GetMapping("/toUpdate")
    public String toUpdate(@RequestParam Integer uid,Model model){
        logger.debug("跳转到修改用户信息页面");
        SysUser sysUser = sysUserService.getUserById(uid);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/update";
    }

    //示例8
    @PostMapping("/update")
    public String modifySave(SysUser user,HttpSession session){
        user.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if(sysUserService.update(user)){
            return "redirect:/user/list";
        }
        return "sysUser/update";
    }

    //示例12
    @PostMapping("/add")
    public String add(@Valid SysUser sysUser, BindingResult bindingResult,HttpSession session){
        if (bindingResult.hasErrors()){
            logger.debug("添加用户失败");
            return "sysUser/add";
        }
        sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.add(sysUser)){
            return "redirect:/user/list";
        }
        return "sysUser/add";
    }

//    //示例16,21
//    @PostMapping("/add")
//    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs",required = false)MultipartFile[] attachs) {
//        String idPicPath = null;
//        if (!idPicPath.isEmpty()) {
//            String path = request.getSession().getServletContext().getRealPath(
//                    "statics" + File.separator + "uploadfiles"
//            );
//            logger.info("上传文件路径" + path);
//            String oldFileName = attach.getOriginalFilename();//原文件名
//            logger.info("原文件名为：" + oldFileName);
//            String suffix = FilenameUtils.getExtension(oldFileName);
//            logger.info("原文件后缀位：" + suffix);
//            String workPicPath = null;
//            String errorInfo = null;
//            boolean flag = true;
//            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
//            logger.info("uploadFile path ===================>" + path);
//            for (int i = 0; i < attachs.length; i++) {
//                MultipartFile attach = attachs[i];
//                if (i == 0) {
//                    errorInfo = "uploadFileError";
//                } else if (i == 1) {
//                    errorInfo = "uploadWpError";
//                }
//                String oldFileName = attach.getOriginalFilename();
//                logger.info("uploadFile oldFileName ===============>" + oldFileName);
//                String prefix = FilenameUtils.getExtension(oldFileName);
//                logger.info("uploadFile prefix ===============>" + prefix);
//                int filesize = 5000000;
//                logger.debug("uploadFile size==================>" + attach.getSize());
//                if (attach.getSize() > filesize) {
//                    request.setAttribute("uploadFileError", "*上传大小不得超过500KB");
//                    return "sysUser/add";
//                } else if (suffix.equalsIgnoreCase("jpg")
//                        || suffix.equalsIgnoreCase("png")
//                        || suffix.equalsIgnoreCase("jpeg")
//                        || suffix.equalsIgnoreCase("pneg")) {
//                    request.setAttribute(errorInfo, "*上传大小不得超过500K");
//                    flag = false;
//                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
//                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
//                    File targetFile = new File(path);
//                    logger.debug("new fileName==========" + attach.getName());
//                    File targetFile = new File(path);
//                    if (!targetFile.exists()) {
//                        targetFile.mkdirs();
//                    }
//                    //保存
//                    try {
//                        attach.transferTo(new File(targetFile, fileName));
//                    } catch (IllegalStateException | IOException e) {
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                        request.setAttribute("uploadFileError", "*上传文件失败！");
//                        return "sysUser/add";
//                        request.setAttribute(errorInfo, "*上传失败！");
//                        flag = false;
//                    }
//                    if (i == 0) {
//                        idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
//                    } else if (i == 1) {
//                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
//                    }
//                    idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
//                    logger.debug("idPicPath" + idPicPath);
//                    logger.debug("workPicPath" + workPicPath);
//                } else {
//                    request.setAttribute("uploadFileError", "*上传图片格式不正确");
//                    return "sysUser/add";
//                    request.setAttribute(errorInfo, "*上传图片格式不正确！");
//                    flag = false;
//                }
//            }
//            sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
//            sysUser.setIdPicPath(idPicPath);
////
////
////        SysUser create = (SysUser) session.getAttribute(Constants.USER_SESSION);
////        sysUser.setCreatedUserId(create.getId());
//            if (sysUserService.add(sysUser)) {
//                return "redirect:/user/list";
//            } else {
//                return "sysUser/add";
//                if (flag) {
//                    sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
//                    sysUser.setIdPicPath(idPicPath);
//                    sysUser.setWorkPicPath(workPicPath);
//                    if (sysUserService.add(sysUser)) {
//                        return "redirect:/user/list";
//                    }
//                }
//            }
//        }
//        return "sysUser/add";
//    }


    @PostMapping("/login")
    public String doLogin(RuntimeException e,HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password){
        logger.debug("登录方法");
        SysUser sysUser = sysUserService.getAccount(account,password);
        if (null != sysUser){
            session.setAttribute(Constants.USER_SESSION,sysUser);
            session.setAttribute("USER_SESSION",sysUser);
            return "redirect:/user/toMain";
        }else {
            session.setAttribute("error","账号或密码错误");
            return "login";
        }

    }

    @GetMapping("/list")
    public String getUserList(Model model, String queryRealName, Integer queryRoleId, @RequestParam(defaultValue = "1")Integer pageIndex){
        List<SysUser> userList = null;
        List<SysRole> sysRoles = null;
        try{
            //设置页面容量
            int pageSize = Constants.pageSize;
            //总数量
            int totalCount = sysUserService.getCount();
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex); // 设置当前页数
            pages.setPageSize(pageSize);       // 设置一页显示数据量
            pages.setTotalCount(totalCount);   // 设置总数据量
            int totalPageCount = pages.getTotalPageCount();

            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.getUserList((pageIndex-1)*pageSize,pageSize,queryRealName,queryRoleId);
            sysRoles = sysRoleService.getAll();
            model.addAttribute("userList",userList);  // 用户信息

            model.addAttribute("totalCount",pages.getTotalCount()); // 分页信息
            model.addAttribute("currentPageNo",pages.getPageNo());
            model.addAttribute("totalPageCount",pages.getTotalPageCount());

            model.addAttribute("queryRealName",queryRealName); // 查询条件回显
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("roleList",sysRoles);



        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "/sysUser/list";
    }
    @ResponseBody // 让返回的内容原样输出到页面（通常用于ajax处理）
    @PostMapping(value = "/checkOldPwd",produces = {"application/json;charset=UTF-8"})
    public String getPwd(String oldPassword, HttpServletResponse response,HttpSession session) throws IOException {
        // 获取登录账号的用户信息
        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        // 查询输入密码是否和数据库用户密码相同
        String account = sysUser.getAccount();
        int pwd = sysUserService.getPwd(oldPassword,account);
        Map<String,String> map = new HashMap<>();
        String result = "true";
        // 判断是否与旧密码相同 true:成功 false:失败
        if (pwd == 1){
            result = "true";
        }else {
            result = "false";
        }

        map.put("result",result);
        return JSON.toJSONString(map);
    }
    @ResponseBody // 让返回的内容原样输出到页面（通常用于ajax处理）
    @PostMapping(value = "/savePassword",produces = "text/html; charset=UTF-8")
    public String savePassword(String newPassword,HttpSession session,HttpServletResponse response) throws IOException {
        // 获取登录账号的用户信息
        SysUser sysUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
        // 调用方法修改密码
        int iRet = sysUserService.savePassword(sysUser.getAccount(),newPassword);

        String result = null;
        if (iRet == 1){
            result = "<script>alert('修改密码成功！');window.location='http://localhost:8080/724_war_exploded/user/toUpdatePwd'</script>";
        }else{
            result = "<script>alert('修改密码失败！');window.location='http://localhost:8080/724_war_exploded/user/toUpdatePwd'</script>";
        }

        return result;
    }

    @ResponseBody  // 让返回的内容原样输出到页面（通常用于ajax处理）
    @GetMapping(value = "/userExist")
    public String getAccountC(String account){
        // 查询是否有相同的账号
        int accountC = sysUserService.getAccountC(account);
        Map<String,Integer> map = new HashMap<>();
        if (accountC > 1){
            map.put("exist", 1);
        }else if (accountC == 0){
            map.put("exist", 0);
        }
        return JSON.toJSONString(map);
    }

    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    // 退出
    @RequestMapping("/logout")
    public String tui(HttpSession session){
        session.removeAttribute("USER_SESSION");
        session.invalidate();
        return "login";
    }
    @GetMapping("/add")
    public String toAdd(){ return "/sysUser/add"; }
    @GetMapping("/toUpdatePwd")
    public String toUpdatePwd(){
        return "/sysUser/updatePassword";
    }

    @RequestMapping(value = "/toLogin")
    public String login(){
        logger.debug("跳转到登录页面");
        return "login";
    }

    // 跳转到登录页面
    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }
}
